package com.hewanglan.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.hewanglan.subject.common.entity.PageResult;
import com.hewanglan.subject.common.enums.IsDeletedFlagEnum;
import com.hewanglan.subject.common.util.IdWorkerUtil;
import com.hewanglan.subject.common.util.LoginUtil;
import com.hewanglan.subject.domain.bo.SubjectInfoBO;
import com.hewanglan.subject.domain.bo.SubjectOptionBO;
import com.hewanglan.subject.domain.convert.SubjectInfoConverter;
import com.hewanglan.subject.domain.handler.subject.SubjectTypeHandler;
import com.hewanglan.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.hewanglan.subject.domain.redis.RedisUtil;
import com.hewanglan.subject.domain.service.SubjectInfoDomainService;
import com.hewanglan.subject.domain.service.SubjectLikedDomainService;
import com.hewanglan.subject.infra.basic.entity.SubjectInfo;
import com.hewanglan.subject.infra.basic.entity.SubjectInfoES;
import com.hewanglan.subject.infra.basic.entity.SubjectLabel;
import com.hewanglan.subject.infra.basic.entity.SubjectMapping;
import com.hewanglan.subject.infra.basic.service.SubjectEsService;
import com.hewanglan.subject.infra.basic.service.SubjectInfoService;
import com.hewanglan.subject.infra.basic.service.SubjectLabelService;
import com.hewanglan.subject.infra.basic.service.SubjectMappingService;
import com.hewanglan.subject.infra.entity.UserInfo;
import com.hewanglan.subject.infra.rpc.UserRPC;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {
    @Resource
    private SubjectInfoService subjectInfoService;
    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;

    @Resource
    private SubjectEsService subjectEsService;

    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    @Resource
    private UserRPC userRPC;

    @Resource
    private RedisUtil redisUtil;

    private static final String RANK_KEY="subject_rank";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        /**
         * 此处使用工厂+策略的模式
         */
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBOToInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo); //先向subject_info这张表中插入该题的信息
        /**
         * 以下还需要根据题目类型向相应题目表中插入该题记录、在subject_mapping表中新增记录
         */
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        subjectInfoBO.setId(subjectInfo.getId());
        handler.add(subjectInfoBO);
        /**
         * 还需要将信息添加到subject_mapping表中
         */
        List<Integer> categoryIds = subjectInfoBO.getCategoryIds();
        List<Integer> labelIds = subjectInfoBO.getLabelIds();
        List<SubjectMapping> mappingList = new LinkedList<>();
        Long subject_id=subjectInfo.getId();

        categoryIds.forEach(categoryId -> {
            labelIds.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subject_id);
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setLabelId(Long.valueOf(labelId));
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                mappingList.add(subjectMapping);
            });
        });
        subjectMappingService.batchInsert(mappingList);
        //还需要同步到es
        SubjectInfoES subjectInfoEs = new SubjectInfoES();
        subjectInfoEs.setDocId(new IdWorkerUtil(1, 1, 1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());

        UserInfo userInfo = userRPC.getUserInfo(LoginUtil.getLoginId());
        String nickName=userInfo.getNickName();
        subjectInfoEs.setCreateUser(nickName);

        subjectEsService.insert(subjectInfoEs);
        //redis放入zSet计入排行榜
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(),1);

    }


    /**
     * 查询题目列表
     * @param subjectInfoBO
     * @return
     */
    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();

        pageResult.setPageNo(subjectInfoBO.getPageNo());//获取要查询第几页的数据
        pageResult.setPageSize(subjectInfoBO.getPageSize());//获取该页要展示的数据

        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();//计算起始索引

        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBOToInfo(subjectInfoBO);

        int count = subjectInfoService.countByCondition(subjectInfo, subjectInfoBO.getCategoryId()
                , subjectInfoBO.getLabelId());//查询满足条件的题目总数
        if (count == 0) {
            return pageResult;
        }
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo, subjectInfoBO.getCategoryId()
                , subjectInfoBO.getLabelId(), start, subjectInfoBO.getPageSize());//分页查询，传条件、偏移量、pageSize

        List<SubjectInfoBO> subjectInfoBOS = SubjectInfoConverter.INSTANCE.convertListInfoToBO(subjectInfoList);

        pageResult.setRecords(subjectInfoBOS);
        pageResult.setTotal(count);

        return pageResult;

    }
    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        SubjectOptionBO optionBO = handler.query(subjectInfo.getId().intValue());
        SubjectInfoBO bo = SubjectInfoConverter.INSTANCE.convertOptionAndInfoToBO(optionBO, subjectInfo);
        /**
         * 填充SubjectInfoBO的labelName列表属性
         */
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        List<String> labelNameList = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
        bo.setLabelName(labelNameList);
        //题目点赞信息 设置当前题目是否被当前用户点赞、当天题目的点赞总数
        bo.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId().toString(),LoginUtil.getLoginId()));
        bo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId().toString()));
        //查询上一题和下一题的题目ID，实现快速刷题功能
        assembleSubjectCursor(subjectInfoBO, bo);
        return bo;
    }

    private void assembleSubjectCursor(SubjectInfoBO subjectInfoBO, SubjectInfoBO bo) {
        Long categoryId = subjectInfoBO.getCategoryId();
        Long labelId = subjectInfoBO.getLabelId();
        Long subjectId = subjectInfoBO.getId();
        if (Objects.isNull(categoryId) || Objects.isNull(labelId)) {
            return;
        }
        Long nextSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 1);//查下一题
        bo.setNextSubjectId(nextSubjectId);
        Long lastSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 0);//0代表查上一题
        bo.setLastSubjectId(lastSubjectId);
    }


    @Override
    public PageResult<SubjectInfoES> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        SubjectInfoES subjectInfoEs = new SubjectInfoES();
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        return subjectEsService.querySubjectList(subjectInfoEs);
    }

    /**
     * 传统数据库实现排行榜
     * @return
     */
//    @Override
//    public List<SubjectInfoBO> getContributeList() {
//        List<SubjectInfo> subjectInfoList= subjectInfoService.getContributeCount();
//       if(CollectionUtils.isEmpty(subjectInfoList))
//       {
//           return Collections.emptyList();
//       }
//       List<SubjectInfoBO> boList=new LinkedList<>();
//       subjectInfoList.forEach(subjectInfo->{
//           SubjectInfoBO subjectInfoBO=new SubjectInfoBO();
//           subjectInfoBO.setSubjectCount(subjectInfo.getSubjectCount());
//           UserInfo userInfo = userRPC.getUserInfo(subjectInfo.getCreatedBy());
//           subjectInfoBO.setCreateUser(userInfo.getNickName());
//           subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
//           boList.add(subjectInfoBO);
//       });
//       return boList;
//    }

    /**
     * 基于redis的zset实现排行榜
     * @return
     */
    @Override
    public List<SubjectInfoBO> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if(log.isInfoEnabled())
        {
            log.info("getContributeList.typedTuples:{}",JSON.toJSONString(typedTuples));
        }
        if(CollectionUtils.isEmpty(typedTuples))
        {
            return Collections.emptyList();
        }
        List<SubjectInfoBO> boList=new LinkedList<>();
        typedTuples.forEach(rank->{
            SubjectInfoBO subjectInfoBO=new SubjectInfoBO();
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            UserInfo userInfo = userRPC.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);
        });
        return boList;
    }

}
